/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.groupbuy.common.service.impl;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.model.Order;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.dao.OrderMapper;
import com.yami.shop.groupbuy.common.api.dto.ApiGroupActivityDto;
import com.yami.shop.groupbuy.common.dao.GroupOrderMapper;
import com.yami.shop.groupbuy.common.dao.GroupTeamMapper;
import com.yami.shop.groupbuy.common.enums.GroupOrderStatusEnum;
import com.yami.shop.groupbuy.common.enums.TeamStatusEnum;
import com.yami.shop.groupbuy.common.model.GroupOrder;
import com.yami.shop.groupbuy.common.model.GroupTeam;
import com.yami.shop.groupbuy.common.service.GroupActivityService;
import com.yami.shop.groupbuy.common.service.GroupPayService;
import com.yami.shop.service.NotifyTemplateService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 拼团支付
 *
 * @author Yami
 */
@Service
@AllArgsConstructor
@Slf4j
public class GroupPayServiceImpl implements GroupPayService {

    private final OrderMapper orderMapper;
    private final GroupTeamMapper groupTeamMapper;
    private final GroupOrderMapper groupOrderMapper;
    private final GroupActivityService groupActivityService;
    private final NotifyTemplateService notifyTemplateService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void paySuccessNoticeHandle(Order order) {
        log.info("处理拼团订单 订单编号：{}", order.getOrderNumber());
        orderMapper.updateToWaitGroup(order.getOrderNumber());
        Long prodId = order.getOrderItems().get(0).getProdId();
        // 获取用户拼团订单信息
        GroupOrder groupOrder = groupOrderMapper.selectOne(new LambdaQueryWrapper<GroupOrder>()
                .eq(GroupOrder::getOrderNumber, order.getOrderNumber()));
        // 获取拼团团队订单
        GroupTeam groupTeam = groupTeamMapper.selectById(groupOrder.getGroupTeamId());

        ApiGroupActivityDto apiGroupActivityInfo = groupActivityService.getApiGroupActivityInfo(groupTeam.getGroupActivityId(), prodId);

        Date now = new Date();
        // 如果为团长则直接开团，否则判断是否拼团已满
        if (Objects.equals(groupOrder.getIdentityType(), 1)) {
            groupTeam.setJoinNum(1);
            groupTeam.setUpdateTime(now);
            groupTeam.setStatus(TeamStatusEnum.IN_GROUP.value());
            groupTeam.setTotalPrice(groupOrder.getPayPrice());
            groupTeam.setStartTime(now);
            groupTeam.setEndTime(DateUtil.offsetMinute(now, apiGroupActivityInfo.getGroupValidTime()));
            groupTeamMapper.updateById(groupTeam);

            groupOrder.setStatus(GroupOrderStatusEnum.SUCCESS.value());
            groupOrderMapper.updateById(groupOrder);

            // 消息推送-开团成功
            notifyTemplateService.sendNotifyOfGroupStart(order,SendType.GROUP_START);
        } else {
            // 参团
            // 判断团是否已满，如果已满则重新开团，如果不是则继续参团
            if (Objects.equals(groupTeam.getStatus(), TeamStatusEnum.SUCCESS.value())) {
                // 满员开团
                GroupTeam newGroupTeam = new GroupTeam();
                newGroupTeam.setJoinNum(1);
                newGroupTeam.setCreateTime(now);
                newGroupTeam.setUpdateTime(now);
                newGroupTeam.setStartTime(now);
                newGroupTeam.setShopId(groupTeam.getShopId());
                newGroupTeam.setTotalPrice(groupOrder.getPayPrice());
                newGroupTeam.setShareUserId(groupOrder.getUserId());
                newGroupTeam.setStatus(TeamStatusEnum.IN_GROUP.value());
                groupTeam.setProdId(groupTeam.getProdId());
                newGroupTeam.setGroupActivityId(groupTeam.getGroupActivityId());
                newGroupTeam.setEndTime(DateUtil.offsetMinute(now, apiGroupActivityInfo.getGroupValidTime()));
                groupTeamMapper.insert(newGroupTeam);

                groupOrder.setIdentityType(1);
                groupOrder.setGroupTeamId(newGroupTeam.getGroupTeamId());
                groupOrder.setStatus(GroupOrderStatusEnum.SUCCESS.value());
                groupOrderMapper.updateById(groupOrder);

                // 消息推送-开团成功、拼团成功、拼团失败
                notifyTemplateService.sendNotifyOfGroupStart(order, SendType.GROUP_START);
            } else if (Objects.equals(groupTeam.getStatus(), TeamStatusEnum.IN_GROUP.value())) {
                // 参团
                groupTeam.setUpdateTime(now);
                groupTeam.setJoinNum(groupTeam.getJoinNum() + 1);
                groupTeam.setTotalPrice(Arith.add(groupTeam.getTotalPrice(), groupOrder.getPayPrice()));
                // 是否已达人数,则修改团信息及订单信息
                if (groupTeam.getJoinNum() >= apiGroupActivityInfo.getGroupNumber()) {
                    // 更新拼团成功
                    groupTeam.setStatus(TeamStatusEnum.SUCCESS.value());
                    List<Order> orders = orderMapper.selectOrderByGroupTeamId(groupTeam.getGroupTeamId());
                    // 查询是否为虚拟商品订单
                    int mold = Objects.isNull(orders.get(0).getOrderMold()) ? 0 : orders.get(0).getOrderMold();
                    // 更新将所有的订单订单待发货
                    if (orderMapper.updateToWaitDelivery(groupTeam.getGroupTeamId(),mold) <= 0) {
                        // 更新拼团订单为待发货失败，请稍后重试
                        throw new YamiShopBindException("yami.group.order.update.fail");
                    }
                    for (Order gOrder : orders) {
                        // 消息推送-开团成功、拼团成功、拼团失败
                        notifyTemplateService.sendNotifyOfGroupStart(gOrder, SendType.GROUP_SUCCESS);
                    }
                }
                groupOrder.setStatus(GroupOrderStatusEnum.SUCCESS.value());
                groupTeamMapper.updateById(groupTeam);
                groupOrderMapper.updateById(groupOrder);
                // 如果满团更新统计信息
                if (groupTeam.getJoinNum() >= apiGroupActivityInfo.getGroupNumber()) {
                    // 更新已成团订单数
//                    groupProd.setGroupOrderCount(groupProd.getGroupOrderCount() + groupTeam.getJoinNum());
//                    // 更新已成团人数
//                    Long count = groupOrderMapper.getHadGroupNumberCount(groupProd.getGroupActivityId(), groupProd.getGroupProdId());
//                    groupProd.setGroupNumberCount(count);
//                        groupProdService.updateById(groupProd);
//                    groupProdService.removeGroupProdCache(groupProd.getGroupProdId());
                }
            }
        }
    }


}
